package cn.yh.register.cmn.service.impl;

import cn.yh.register.cmn.listener.ExcelLinstenter;
import cn.yh.register.cmn.mapper.DictMapper;
import cn.yh.register.cmn.service.DictService;
import cn.yh.register.model.cmn.Dict;
import cn.yh.register.vo.cmn.DictEeVo;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {


    /**
     * 根据Id查询子数据
     * @param id 字典Id
     * @return 子数据列表
     */

    @Override
    @Cacheable(value = "dict",keyGenerator="keyGenerator")
    public List<Dict> findChildData(Long id) {
        List<Dict> dicts = baseMapper.selectList(new LambdaQueryWrapper<Dict>().eq(Dict::getParentId, id));
//        dicts.forEach(dict -> dict.setHasChildren(this.hasChildren(dict.getId())));

        //处理hasChildren属性 看是否有子节点
        for (Dict dict : dicts) {
            Boolean flag = this.hasChildren(dict.getId());
            dict.setHasChildren(flag);
        }

        return dicts;
    }

    /**
     * 导出
     * @param response
     */
    @Override
    public void exportData(HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("数据字典", "UTF-8");
            //设置响应头 告诉浏览器以附件的方式打开(下载)
            response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
            //查询数据
            List<Dict> dictList = baseMapper.selectList(null);
            //转为vo类型
            List<DictEeVo> voVoList = new ArrayList<>(dictList.size());
            for(Dict dict : dictList) {
                DictEeVo dictVo = new DictEeVo();
                BeanUtils.copyProperties(dict,dictVo);
                voVoList.add(dictVo);
            }
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("数据字典").doWrite(voVoList);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 导入数据
     * @param file 文件对象
     */
    @Override
    @CacheEvict(value = "dict",allEntries = true)
    public void importDtata(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new ExcelLinstenter(baseMapper)).sheet("数据字典").doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取字典名称
     * @param dictCode 字典编码
     * @param value    字典值
     * @return 字典名称
     */
    @Override
    public String getNameByDictCodeAndValue(String dictCode, String value) {
        Dict dict=new Dict();
        if (StringUtils.isEmpty(dictCode)) {
            //字典值可以唯一确定一条字典数据
            dict = baseMapper.selectOne(new LambdaQueryWrapper<Dict>()
                    .eq(Dict::getValue, value));
        }else if ("ROOT".equals(dictCode)){
            //字典编码可以唯一确定一条字典数据
            dict=this.getByDictCode(dictCode);
        }
        else {
            //结合字典编码查询一条字典数据
            Dict byDictCode = this.getByDictCode(dictCode);
            // 将上条结果的id作为父id 和 value 一块查询
            dict = baseMapper.selectOne(new LambdaQueryWrapper<Dict>()
                    .eq(Dict::getParentId,byDictCode.getId())
                    .eq(Dict::getValue,value));
        }
        return dict.getName();
    }

    /**
     * 根据字典编码获取子数据
     * @param dictCode 字典编码
     * @return 子数据列表
     */
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        Dict dict = this.getByDictCode(dictCode);
        if (dict != null) {
            return this.findChildData(dict.getId());
        }
        return null;
    }

    //  根据字典编码查询字典
    private Dict getByDictCode(String dictCode) {
        return baseMapper.selectOne(new LambdaQueryWrapper<Dict>()
                .eq(Dict::getDictCode, dictCode));
    }
    //看看是否有子节点
    private Boolean hasChildren(Long id) {
        Integer count = baseMapper.selectCount(new LambdaQueryWrapper<Dict>().eq(Dict::getParentId, id));
        return count > 0;
    }

}
